package org.aeon.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.aeon.dao.ChatGroupDao;
import org.aeon.dao.UserGroupRelationDao;
import org.aeon.entity.User;
import org.aeon.entity.UserGroupRelation;
import org.aeon.entity.UserRelation;
import org.aeon.entity.dto.UserDto;
import org.aeon.service.UserGroupRelationService;
import org.aeon.service.factory.ChatGroupServiceFactory;
import org.aeon.service.factory.UserRelationServiceFactory;
import org.aeon.service.factory.UserServiceFactory;
import org.aeon.utils.MybatisUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.modelmapper.ModelMapper;

import java.util.*;

@Slf4j
public class UserGroupRelationServiceImpl implements UserGroupRelationService {
    @Override
    public int insertBatchUserGroupRelation(Long groupId, Long... userIds) {
        return switch (userIds.length) {
            case 0 -> 0;
            case 1 -> {
                // 单个插入
                SqlSession sqlSession = MybatisUtils.getSqlSession(false);
                try {
                    final UserGroupRelation entity = new UserGroupRelation();
                    entity.setGroupId(groupId);
                    entity.setUserId(userIds[0]);
                    entity.setJoinTime(new Date());
                    // 添加成员
                    final UserGroupRelationDao groupRelationDao = sqlSession.getMapper(UserGroupRelationDao.class);
                    final int insert = groupRelationDao.insert(entity);
                    // 修改群聊人数
                    final ChatGroupDao groupDao = sqlSession.getMapper(ChatGroupDao.class);
                    groupDao.updatePeopleCount(groupId, groupDao.getPeopleCount(groupId) + insert);
                    // 提交
                    sqlSession.commit();
                    sqlSession.clearCache();
                    yield insert;
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    // 出错回滚
                    sqlSession.rollback();
                    yield -1;
                } finally {
                    if (sqlSession != null)
                        sqlSession.close();
                }
            }
            default -> {
                // 多个插入
                SqlSession sqlSession = MybatisUtils.getSqlSession(ExecutorType.BATCH, false);
                try {
                    final UserGroupRelationDao mapper = sqlSession.getMapper(UserGroupRelationDao.class);
                    Arrays.stream(userIds).forEach(userId -> {
                        final UserGroupRelation entity = new UserGroupRelation();
                        entity.setGroupId(groupId);
                        entity.setUserId(userId);
                        entity.setJoinTime(new Date());
                        mapper.insert(entity);
                    });
                    // 修改群聊人数
                    final ChatGroupDao groupDao = sqlSession.getMapper(ChatGroupDao.class);
                    groupDao.updatePeopleCount(groupId, groupDao.getPeopleCount(groupId) + userIds.length);
                    // 提交
                    sqlSession.commit();
                    sqlSession.clearCache();
                    yield userIds.length;
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    // 出错回滚
                    sqlSession.rollback();
                    yield -1;
                } finally {
                    if (sqlSession != null)
                        sqlSession.close();
                }
            }
        };

    }

    @Override
    public int deleteUserGroupRelation(Long groupId, Long userId) {
        try (SqlSession sqlSession = MybatisUtils.getSqlSession(true)) {
            final UserGroupRelationDao mapper = sqlSession.getMapper(UserGroupRelationDao.class);
            return mapper.delete(groupId, userId);
        }
    }

    @Override
    public int fillGroup(Long groupId, Long userId, Set<Long> members) {
        // 判断是否存在
        if (ChatGroupServiceFactory.getService().isChatGroupExist(groupId)) {
            // 好友检测
            final Long[] userIds = members.stream().filter(item -> {
                if (Objects.equals(userId, item)) return true;
                // 查询关系
                final UserRelation relation = UserRelationServiceFactory.getService().queryRelation(userId, item);
                // 有且为好友关系
                return relation != null && relation.getIsFriend();
            }).toArray(Long[]::new);
            // 批量插入
            return insertBatchUserGroupRelation(groupId, userIds);
        }
        return -1;
    }

    @Override
    public Set<UserDto> getMembers(Long groupId) {
        try (SqlSession sqlSession = MybatisUtils.getSqlSession(true)) {
            final UserGroupRelationDao mapper = sqlSession.getMapper(UserGroupRelationDao.class);
            Set<UserDto> members = new HashSet<>();
            // 获取所有组员并遍历
            for (Long userId : mapper.getMembers(groupId)) {
                final User user = UserServiceFactory.getService().getUserById(userId);
                final UserDto aUserDto = new ModelMapper().map(user, UserDto.class);
                members.add(aUserDto);
            }
            return members;
        }
    }

    @Override
    public boolean isGroupMember(Long groupId, Long userId) {
        try (SqlSession sqlSession = MybatisUtils.getSqlSession(true)) {
            final UserGroupRelationDao mapper = sqlSession.getMapper(UserGroupRelationDao.class);
            UserGroupRelation entity = mapper.getMember(groupId, userId);
            return entity != null;
        }
    }

    @Override
    public List<Long> getGroups(Long userId) {
        try (SqlSession sqlSession = MybatisUtils.getSqlSession(true)) {
            final UserGroupRelationDao mapper = sqlSession.getMapper(UserGroupRelationDao.class);
            List<UserGroupRelation> entities = mapper.getGroupsByUserId(userId);
            return entities.stream().map(UserGroupRelation::getGroupId).toList();
        }
    }

}
